/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: Frank
 * 系统版本: 1.0.0
 * 开发人员: Frank
 * 开发时间: 2020/3/5 22:11
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.common.jms.subscribe;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import com.hazelcast.core.MessageListener;
import com.spring.arch.common.jms.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息订阅者
 *
 * @author Frank
 * @version 1.0.0.1
 * @since 2020/3/5 22:11
 */
public abstract class MessageSubscriber implements MessageListener<Message> {

    protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    private final ITopic<Message> topic;

    private final HazelcastInstance hzInstance;

    public MessageSubscriber(String topicName) {
        this.hzInstance = Hazelcast.newHazelcastInstance();
        this.topic = createTopic(topicName);
        topic.addMessageListener(this);
    }

    public MessageSubscriber(HazelcastInstance hzInstance, String topicName) {
        this.hzInstance = hzInstance;
        this.topic = createTopic(topicName);
        topic.addMessageListener(this);
    }

    private ITopic<Message> createTopic(String topicName) {
        return hzInstance.getTopic(topicName);
    }

    @Override
    public void onMessage(com.hazelcast.core.Message<Message> message) {
        LOGGER.info("<<<<<<<<<Received: {}", message.getMessageObject().toString());
        // 处理消息
        process(message);
    }

    protected abstract void process(com.hazelcast.core.Message<Message> message);


}
